package com.scuec.groupfive.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.scuec.groupfive.entity.Post;
import com.scuec.groupfive.entity.PostComment;
import com.scuec.groupfive.entity.PostFavorite;
import com.scuec.groupfive.entity.vo.UserPostVO;
import com.scuec.groupfive.mapper.UserPostMapper;
import com.scuec.groupfive.service.UserPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserPostServiceImpl implements UserPostService {

    @Autowired
    private UserPostMapper userPostMapper;

    @Override
    public PageInfo<UserPostVO> getFavoritesByUserId(Long userId, Integer current, Integer size) {
        // 使用PageHelper设置分页参数
        Page<Object> page = PageHelper.startPage(current, size);
        // 调用Mapper查询（注意：原LIMIT分页需改为普通查询）
        List<PostFavorite> favorites = userPostMapper.selectFavoritesByUserId(userId);
        // 转换为VO列表
        List<UserPostVO> voList = favorites.stream().map(favorite -> {
            Post post = userPostMapper.selectPostById(favorite.getPostId());
            List<PostComment> comments = userPostMapper.selectCommentsByPostId(favorite.getPostId());
            return new UserPostVO(post, favorite, comments);
        }).collect(Collectors.toList());

//        获取总条数
        long total = page.getTotal();
        // 用PageInfo包装结果
        PageInfo<UserPostVO> userPostVOPageInfo = new PageInfo<>(voList);
        userPostVOPageInfo.setTotal(total);
        return userPostVOPageInfo;
//        return new PageInfo<>(voList);
    }

    @Override
    public boolean deleteFavorite(Long favoriteId) {
        return userPostMapper.deleteFavorite(favoriteId) > 0;
    }
}